using System;
using Microsoft.SPOT;
using GHIElectronics.NETMF.Hardware;
using Microsoft.SPOT.Hardware;
using System.Threading;

namespace FEZ_Panda_II_Application1
{
    public class Boom
    {
        PWM powerpin = new PWM(AstoXPinMap.MotorPWMPin);
        OutputPort dir = new OutputPort(AstoXPinMap.MotorDirPin, false);


        public Boom()
        {
            powerpin.Set(false);
            powerpin.SetPulse(0, 0);
            
            FlightControl.FlightPhaseChanged += new FlightPhaseChangeHandler(FlightControl_FlightPhaseChanged);
        }

        void FlightControl_FlightPhaseChanged(FlightPhases newphase)
        {
            if (newphase == FlightPhases.Extend)
            {
                FlightControl.CurrentPhase = FlightPhases.Extending;
                Open();
                
            }
            else if (newphase == FlightPhases.Retract)
            {
                FlightControl.CurrentPhase = FlightPhases.Retracting;
                Close();                
            }
            else if (newphase == FlightPhases.Retracted)
            {
                FlightControl.CurrentPhase = FlightPhases.Descent;
            }
        }


        private void Open()
        {
            dir.Write(false);
            powerpin.SetPulse(1000, 1000);
            Timer t = new Timer(new TimerCallback((o) => 
            {
                powerpin.SetPulse(0, 0);
                FlightControl.CurrentPhase = FlightPhases.Extended;
            }), null, 1000 * 20,0);

            
        }

        private void Close()
        {
            dir.Write(true);
            powerpin.SetPulse(1000, 1000);
            Timer t = new Timer(new TimerCallback((o) =>
            {
                powerpin.SetPulse(0, 0);
                FlightControl.CurrentPhase = FlightPhases.Retracted;
            }), null, 1000 * 20, 0);

        }
    }
}
